<template>
  <div class="account-management">
    <!-- 顶部操作栏 -->
    <div class="top-banner">
      <div class="mb-4">
        <el-button type="primary" @click="openDrawer()">新增</el-button>
      </div>
      <div>
        <el-input v-model="input" style="width: 240px" :prefix-icon="Search" placeholder="请输入" />
      </div>
    </div>

    <!-- 表格展示 -->
    <div class="cont-table">
      <el-table :data="userList" border stripe height="auto" class="custom-table" v-loading="loading">
        <!-- 序号列 -->
        <el-table-column type="index" label="序号" width="60" align="center" />

        <!-- 动态表头 -->
        <template v-for="(item, index) in tabHeading" :key="index">
          <el-table-column
            :prop="item.prop"
            :label="item.label"
            :width="item.width"
            :min-width="item.minWidth"
            align="center"
            show-overflow-tooltip
          >
            <template #default="{ row }">
              <!-- 特殊字段处理示例 -->
              <!-- 身份字段用 tag 渲染 -->
              <el-tag v-if="item.isTag" :type="getTagType(row.rank.rankname)">
                {{ row.rank.rankname }}
              </el-tag>
              <!-- 默认展示 -->
              <span v-else>{{ row[item.prop] }}</span>
            </template>
          </el-table-column>
        </template>

        <!-- 操作列 -->
        <el-table-column fixed="right" label="操作" min-width="200">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="editDetailDrawer(row)">编辑</el-button>
            <!-- 删除按钮，判断是否为超级管理员 -->
            <el-button
              link
              type="danger"
              size="small"
              :disabled="row.rankid === 1"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="footer_pag">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="pageSizes"
        layout="->,total, prev, pager, next,sizes"
        :total="total"
      />
    </div>

    <!-- 抽屉：新增 / 编辑账号 -->
    <el-drawer v-model="drawer" :size="600" @close="resetForm">
      <template #header="{ titleId, titleClass }">
        <div class="drawer-header">
          <h4 :id="titleId" :class="[titleClass, 'drawer-title']">
            {{ isEdit ? '编辑账号' : '新增账号' }}
          </h4>
        </div>
      </template>

      <el-form
        :model="formData"
        :rules="rules"
        :key="formKey"
        ref="formRef"
        label-width="80px"
        label-position="left"
      >
        <!-- 账号 -->
        <el-form-item label="账号" prop="username">
          <el-input v-model="formData.username" placeholder="请输入账号"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            show-password
            v-model="formData.password"
            type="password"
            placeholder="请修改密码"
          ></el-input>
        </el-form-item>
        <!-- 员工姓名 -->
        <el-form-item label="员工姓名" prop="staffname">
          <el-input v-model="formData.staffname" placeholder="请输入员工姓名"></el-input>
        </el-form-item>
        <!-- 身份 -->
        <el-form-item label="身份" prop="rankid" v-if="!isSuperAdmin">
          <el-select v-model="formData.rankid" placeholder="请选择身份">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.rankname"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 提交按钮 -->
        <div class="bottomBtn">
          <el-button @click="drawer = false" type="info" icon="Close">取消</el-button>
          <el-button
            :type="isEdit ? 'warning' : 'primary'"
            :style="{ marginRight: '20px' }"
            :icon="isEdit ? Edit : DocumentAdd"
            @click="isEdit ? handleUpdate() : handleSubmit()"
          >
            {{ isEdit ? '修改' : '提交' }}
          </el-button>
        </div>
      </el-form>
    </el-drawer>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted, computed, watch, nextTick } from 'vue';
import { Search, Edit, DocumentAdd } from '@element-plus/icons-vue';
import { useUserStore } from '@/api/store';
import api from '@/api/httpApi.js';
import { showError, showSuccess, showConfirm, date } from '@/utils/plugs';

// ====== 用户状态相关 ======
const userStore = useUserStore();
const userId = userStore.userInfo.id;
const userList = ref([]);
const roleList = ref([]);
const loading = ref(false);
// 判断是否是超级管理员（用于控制是否显示身份选择框）
const isSuperAdmin = computed(() => {
  return formData.value.rankid === 1;
});

// ====== 表单 & 弹窗状态 ======
const input = ref('');
const drawer = ref(false);
const formRef = ref(null);
const isEdit = ref(false);
const formData = ref({
  userid: userId,
  username: '',
  password: '',
  staffname: '',
  rankid: null,
});
const formKey = ref(0);

// ====== 分页配置 ======
const pageSize = ref(10);
const pageSizes = ref([10, 20, 30]);
const currentPage = ref(1);
const total = ref(0);

// ====== 表头配置 ======
const tabHeading = [
  { label: '用户名', prop: 'username', minWidth: 120 },
  { label: '姓名', prop: 'staffname', minWidth: 100 },
  { label: '身份', prop: 'rank', minWidth: 100, isTag: true },
  { label: '创建时间', prop: 'createtime', minWidth: 180 },
  { label: '删除时间', prop: 'deletetime', minWidth: 180 },
];

// ====== 角色标签颜色映射 ======
function getTagType(accountType) {
  switch (accountType) {
    case '成员':
      return 'info';
    case '超级管理员':
      return 'danger';
    case '管理员':
      return 'warning';
    default:
      return 'info';
  }
}

// ====== 获取用户列表数据 ======
const fetchUserList = async (page = 1, limit = 10) => {
  loading.value = true;
  if (!userId) {
    showError('用户信息未加载完成，请稍后重试');
    return;
  }

  try {
    const userData = await api.getUserList({ userid: userId, page, limit });
    const transformedList = userData.data.userList.map((user) => ({
      ...user,
      createtime: date(user.createtime, 'yyyy-MM-dd HH:mm:ss'),
      deletetime: user.deletetime ? date(user.deletetime, 'yyyy-MM-dd HH:mm:ss') : '-',
    }));
    userList.value = transformedList;
    total.value = userData.data.count;
  } catch (err) {
    console.error('获取用户列表失败:', err);
  } finally {
    loading.value = false;
  }
};

// ====== 获取角色列表 ======
onMounted(async () => {
  fetchUserList(); // 获取用户列表
  const roleData = await api.getRoleList({ userid: userId });
  roleList.value = roleData.data;
});

// ====== 表单验证规则 ======
const rules = computed(() => {
  const baseRules = {
    username: [
      { required: true, message: '账号不能为空', trigger: 'blur' },
      { min: 6, max: 20, message: '账号长度在6到20个字符之间', trigger: 'blur' },
    ],
    staffname: [
      { required: true, message: '员工姓名不能为空', trigger: 'blur' },
      { max: 30, message: '姓名不能超过30个字符', trigger: 'blur' },
    ],
    rankid: [{ required: true, message: '请选择账号身份', trigger: 'change' }],
  };

  if (!isEdit.value) {
    baseRules.password = [
      { required: true, message: '密码不能为空', trigger: 'blur' },
      { min: 6, max: 20, message: '密码长度在6到20个字符之间', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          const regex = /^(?=.*[A-Za-z])[A-Za-z0-9!@#$%^&*]{6,20}$/;
          if (!regex.test(value)) {
            callback(new Error('密码必须包含字母，且只能包含字母、数字或常见符号'));
          } else {
            callback();
          }
        },
        trigger: 'blur',
      },
    ];
  }

  return baseRules;
});

// ====== 分页监听 ======
watch([currentPage, pageSize], ([newPage, newLimit]) => {
  fetchUserList(newPage, newLimit);
});

// ====== 弹窗操作 ======
function openDrawer() {
  isEdit.value = false;
  resetForm();
  drawer.value = true;
}

function editDetailDrawer(row) {
  isEdit.value = true;
  drawer.value = true;

  formData.value = {
    superid: userId,
    userid: row.id,
    username: row.username,
    staffname: row.staffname,
    password: row.password || '',
    rankid: Number(row.rankid),
  };
}

function resetForm() {
  formData.value = {
    superid: userId,
    userid: '',
    username: '',
    password: '',
    staffname: '',
    rankid: null,
  };

  formKey.value++;
}

// ====== 提交新增账号 ======
function handleSubmit() {
  formRef.value.validate((valid) => {
    if (valid) {
      api.registerUser({
        userid: userId,
        username: formData.value.username,
        password: formData.value.password,
        staffname: formData.value.staffname,
        rankid: formData.value.rankid,
      })
        .then((res) => {
          if (res.status === 1) {
            fetchUserList();
            showSuccess(res.message);
            formRef.value.resetFields();
          } else {
            showError(res.message);
          }
        })
        .catch(() => {
          showError('新增失败');
        });

      drawer.value = false;
    } else {
      return false;
    }
  });
}

// ====== 更新账号信息 ======
function handleUpdate() {
  formRef.value.validate((valid) => {
    if (valid) {
      if (formData.value.rankid === 1) {
        api.updateAdminUser({
          userid: formData.value.userid,
          username: formData.value.username,
          password: formData.value.password,
          staffname: formData.value.staffname,
          superid: userId,
        }).then((res) => {
          if (res.status === 1) {
            fetchUserList();
            showSuccess(res.message);
            drawer.value = false;
          } else {
            showError(res.message);
          }
        });
      } else {
        api.updateAdminUser(formData.value)
          .then((res) => {
            if (res.status === 1) {
              fetchUserList();
              showSuccess(res.message);
              drawer.value = false;
            } else {
              showError(res.message);
            }
          })
          .catch(() => {
            showError('修改失败');
          });
      }
    } else {
      showError('表单验证失败');
      return false;
    }
  });
}

// ====== 删除用户 ======
const handleDelete = async (row) => {
  const isConfirmed = await showConfirm('您确定要删除该用户吗？');
  if (!isConfirmed) return;

  try {
    const res = await api.deleteUser({ superid: userId, userid: row.id });
    if (res.status === 1) {
      fetchUserList();
      showSuccess('删除成功');
    } else {
      showError(res.message);
    }
  } catch {
    showError('删除失败');
  }
};
</script>

<style lang="less" scoped>
@import "@/assets/scss/web.scss";

.account-management {
  .top-banner {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }

  .footer_pag {
    margin: 20px;
  }

  .el-drawer__body {
    padding: 20px;
  }

  .el-form-item {
    margin-bottom: 20px;
  }

  .el-button--text {
    color: #409eff;
  }

  .detail-item {
    font-family: PingFang SC, PingFang SC;
    font-weight: 500;
    font-size: 14px;
    color: #303133;
  }

  .detail-item span:first-child {
    width: 80px;
    text-align: left;
    margin-right: 10px;
    font-size: 14px;
    color: #303133;
  }

  .drawer-header {
    width: 560px;
    height: 56px;
    background: #fafafa;
    border: 1px solid #dcdfe6;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: -20px -40px 0px -20px;
  }

  .drawer-title {
    padding-left: 15px;
    margin-top: 15px;
    font-size: 18px;
    color: #303133;
  }

  .bottomBtn {
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 52px;
    background: #fafafa;
    border: 1px solid #dcdfe6;
    left: 0;
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }

  .auth-item {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 8px;
  }
}
</style>